﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using SmartSpace.Web;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebApp._console.page
{
    public partial class template_add : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            _ctlLinkBack.NavigateUrl = "./Template-list.aspx";
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();

            if (_ctlPreviewImage.HasFile)
            {
                SmartSpace.Core.Image image = new SmartSpace.Core.Image();
                image.Id = Guid.NewGuid();
                image.Data = _ctlPreviewImage.FileBytes;
                image.Extension = new FileInfo(_ctlPreviewImage.FileName).Extension;

                if (service.SaveImage(image))
                {
                    PageTemplate template = new PageTemplate();
                    template.Id = Guid.NewGuid();
                    template.SiteId = SsSite.Current.Id;
                    template.Code = _ctlEditName.Text;
                    template.Caption = _ctlEditCaption.Text;
                    template.Data = _ctlFileUpload.FileBytes;
                    template.PreviewImageId = image.Id;

                    if (service.SavePageTemplate(template))
                    {
                        System.IO.File.WriteAllBytes(Server.MapPath("~/_templates/_page/" + template.Code + ".ascx"), template.Data);

                        Response.Redirect(_ctlLinkBack.NavigateUrl);
                    }
                }
            }
        }
    }
}